<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
/**
 * 获取一个随机数.
 * @param int $num
 * @return float|int
 */
function rand_code($num = 4)
{
    $min = pow(10, ($num - 1));
    $max = $min * 9;
    --$num;
    while ($num > 0) {
        $max += pow(10, ($num - 1)) * 9;
        --$num;
    }
    return rand($min, $max);
}

/*
 * 容器实例
 */
if (! function_exists('container')) {
    function container()
    {
        return \Hyperf\Utils\ApplicationContext::getContainer();
    }
}

/*
 * 容器实例
 */
if (! function_exists('event_dispatcher')) {
    function event_dispatcher()
    {
        return container()->get(\Hyperf\Event\EventDispatcher::class);
    }
}

/*
 * redis 客户端实例
 */
if (! function_exists('redis')) {
    function redis()
    {
        return container()->get(\Hyperf\Redis\Redis::class);
    }
}

/**
 * Server 实例 基于 Swoole Server.
 *
 * @return \Swoole\Coroutine\Server|\Swoole\Server
 */
function server()
{
    return container()->get(\Hyperf\Server\ServerFactory::class)->getServer()->getServer();
}

function get_order_no()
{
    $snow = new \App\Utils\SnowflakeIdWorker(1);
    return $snow->nextId();
}

/**
 * 将数据中的int、float类型数据转成string.
 * @param $data
 */
function field_to_string($data)
{
    if (is_array($data)) {
        foreach ($data as &$value) {
            $value = field_to_string($value);
        }
        unset($value);
    } else {
        if (is_int($data) || is_float($data)) {
            $data = strval($data);
        }
    }
    return $data;
}
